package com.xl.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xl.yygh.cmn.listener.DictListener;
import com.xl.yygh.cmn.mapper.DictMapper;
import com.xl.yygh.cmn.service.DictService;
import com.xl.yygh.model.model.cmn.Dict;
import com.xl.yygh.model.vo.cmn.DictEeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author XiangLiang
 * @date 2023/10/21 18:55
 * @description
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    /**
     * 根据数据id查询子数据列表
     * @param id 节点ID
     */
    @Override
    @Cacheable(value = "dict", keyGenerator = "keyGenerator")
    public List<Dict> findChildData(Long id) {
        List<Dict> dictList = baseMapper.selectList(new QueryWrapper<Dict>().eq("parent_id", id));
        for (Dict dict : dictList) {
            Long dictId = dict.getId();
            Boolean hasChildren = this.hasChildren(dictId);
            dict.setHasChildren(hasChildren);
        }
        return dictList;
    }

    /**
     * 判断该节点是否有子节点
     * @param id 节点ID
     * @return 该节点是否有子节点
     */
    public Boolean hasChildren(Long id) {
        Integer count = baseMapper.selectCount(new QueryWrapper<Dict>().eq("parent_id", id));
        return count > 0;
    }

    /**
     * 数据字典导出
     * @param response Http请求
     */
    @Override
    public void exportData(HttpServletResponse response) {
        // 设置响应头信息
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // URLEncoder.encode() 防止中文乱码
        String fileName = null;
        try {
            fileName = URLEncoder.encode("数据字典", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        // 链接设置为下载形式
        response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");

        // 获取数据并将 List<Dict> 转化为 List<DictEeVo>
        List<Dict> dictList = baseMapper.selectList(null);
        List<DictEeVo> resultList = new ArrayList<DictEeVo>(dictList.size());
        for (Dict dict : dictList) {
            DictEeVo dictEeVo = new DictEeVo();
            BeanUtils.copyProperties(dict, dictEeVo);
            resultList.add(dictEeVo);
        }
        // 导出
        try {
            EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("数据字典").doWrite(resultList);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 数据字典导入
     * allEntries = true: 方法调用后清空所有缓存
     * @param file 导入的多媒体文件
     * @return 导入结果
     */
    @Override
    @CacheEvict(value = "dict", allEntries = true)
    public void importDictData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), DictEeVo.class, new DictListener(baseMapper)).sheet().doRead();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 根据字典code和value获取字典name
     * @param parentDictCode 字典code
     * @param value 字典value值
     * @return 字典name
     */
    @Override
    public String getNameByParentDictCodeAndValue(String parentDictCode, String value) {
        if (StringUtils.isEmpty(parentDictCode)) {
            Dict dict = baseMapper.selectOne(new QueryWrapper<Dict>().eq("value", value));
            String dictName = dict.getName();
            return dictName;
        } else {
            Dict dict = baseMapper.selectOne(new QueryWrapper<Dict>()
                    .eq("dict_code", parentDictCode));
            if (dict == null) {
                return "";
            }
            Long parentId = dict.getId();
            Dict dictSub = baseMapper.selectOne(new QueryWrapper<Dict>()
                    .eq("parent_id", parentId)
                    .eq("value", value));
            return dictSub.getName();
        }
    }

    /**
     * 根据dictCode获取对应实体
     * @param dictCode 字典编码
     * @return Dict实体
     */
    private Dict getDictByDictCode(String dictCode) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code",dictCode);
        Dict codeDict = baseMapper.selectOne(wrapper);
        return codeDict;
    }

    /**
     * 根据dictCode获取下级节点
     * @param dictCode 字典编码
     * @return 节点List
     */
    @Override
    public List<Dict> findByDictCode(String dictCode) {
        // 根据dictCode获取父节点dict实体
        Dict dict = this.getDictByDictCode(dictCode);
        // 根据父节点ID获取其子节点列表
        List<Dict> childData = this.findChildData(dict.getId());
        return childData;
    }
}
